// pages/level/level.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    persuadeValue: 50,
    aiReply: '',
    playerInput: '',
    bgImage: '/images/image2.jpg',
    roleImage: '/images/image2.jpg',
    type: 'guard'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let type = options.type || 'guard';
    let bgImage = '/images/image2.jpg';
    let roleImage = '/images/image2.jpg';
    let aiReply = '守卫：你是谁？为何要进城？';
    if (type === 'minister') {
      bgImage = '/images/image3.jpg';
      roleImage = '/images/image3.jpg';
      aiReply = '宰相：你有何贵干？';
    } else if (type === 'king') {
      bgImage = '/images/image4.jpg';
      roleImage = '/images/image4.jpg';
      aiReply = '国王：你为何觐见？';
    }
    this.setData({
      bgImage,
      roleImage,
      aiReply,
      persuadeValue: 50,
      playerInput: '',
      type
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onInput(e) {
    this.setData({ playerInput: e.detail.value });
  },

  onSend() {
    const { playerInput, type } = this.data;
    if (!playerInput.trim()) return;
    // 调用智能体API
    this.callAIAPI(type, playerInput);
  },

  callAIAPI(type, input) {
    const apiUrl = 'https://api.moonshot.cn/v1/chat/completions';
    const apiKey = 'sk-3cBbsvoocPSfcKfM1fQ3iWghywuuOpUr6EVF84ZOYeyardq2'; // 更新为新的 Moonshot API 密钥
    const prompt = this.getPromptByType(type, input);
    console.log('发送请求到API:', { apiUrl, prompt }); // 添加调试日志

    // 检查域名是否已配置为合法域名
    wx.request({
      url: apiUrl,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      data: {
        prompt: prompt,
        max_tokens: 100
      },
      success: (res) => {
        console.log('API响应成功:', res.data); // 添加调试日志
        const aiReply = res.data.choices[0].text.trim();
        let persuadeValue = this.data.persuadeValue;
        // 根据AI回复调整说服值
        if (aiReply.includes('同意') || aiReply.includes('通过')) {
          persuadeValue += 10;
        } else if (aiReply.includes('拒绝') || aiReply.includes('失败')) {
          persuadeValue -= 10;
        }
        if (persuadeValue > 100) persuadeValue = 100;
        if (persuadeValue < 0) persuadeValue = 0;
        this.setData({
          aiReply,
          persuadeValue,
          playerInput: ''
        });
        // 检查是否通关或失败
        if (persuadeValue >= 100) {
          wx.showModal({
            title: '恭喜',
            content: '你成功说服了对方！',
            showCancel: false,
            success: () => {
              wx.navigateBack();
            }
          });
        } else if (persuadeValue <= 0) {
          wx.showModal({
            title: '挑战失败',
            content: '说服值已归零，请重新开始！',
            showCancel: false,
            success: () => {
              this.onRestart();
            }
          });
        }
      },
      fail: (err) => {
        console.error('API调用失败', err);
        console.error('错误详情:', err.errMsg); // 添加更详细的错误日志
        wx.showToast({
          title: '连接失败，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  getPromptByType(type, input) {
    let prompt = '';
    if (type === 'guard') {
      prompt = `守卫：${input}\n请判断玩家是否说服了守卫进城。如果玩家证明自己不是坏人，回复"同意"；否则回复"拒绝"。`;
    } else if (type === 'minister') {
      prompt = `宰相：${input}\n请判断玩家是否以利益允诺打动了宰相。如果玩家承诺了利益，回复"同意"；否则回复"拒绝"。`;
    } else if (type === 'king') {
      prompt = `国王：${input}\n请判断玩家是否保证会好好照顾国王的女儿。如果玩家承诺了照顾公主，回复"同意"；否则回复"拒绝"。`;
    }
    return prompt;
  },

  onRestart() {
    this.onLoad({ type: this.data.type });
  },

  onBackHome() {
    wx.reLaunch({ url: '/pages/index/index' });
  }
})